package com.brownalexis.application.controller;

import com.brownalexis.application.enums.ResponseCode;
import com.brownalexis.application.params.FileParams;
import com.brownalexis.application.query.FileChunkQuery;
import com.brownalexis.application.utils.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
 * @Author: brownalexis
 * @Date: 2024/04/18 15:16
 * @Description:
 */
@RestController
@RequestMapping("/upload")
public class UploadController {


    @Autowired
    private FileStorageService fileStorageService;

    @RequestMapping("/fragment")
    public ApiResponse fragmentUpload( @RequestParam("file") MultipartFile file,
                                       @ModelAttribute FileParams params) throws IOException {
        fileStorageService.saveChunk(file,params);
        return  ApiResponse.success();
    }
    @PostMapping("/merge")
    public ApiResponse<String> mergeFile(@RequestBody FileParams params) {
        try {
            fileStorageService.mergeFile(params.getFileName(),params.getChunks(),params.getIdentifier());
            return ApiResponse.success("File merged");
        } catch (IOException e) {
            return ApiResponse.error(ResponseCode.INTERNAL_SERVER_ERROR,"Failed to merge file");
        }
    }

    @DeleteMapping("/files/delete")
    public ApiResponse<String> deleteFileChunks(@RequestParam("fileName") String fileName,
                                                   @RequestParam("identifier") String identifier,
                                                @RequestParam("userId")  Long userId) {
        try {
            fileStorageService.deleteFileChunks(fileName, identifier,userId);
            return ApiResponse.success("File chunks deleted successfully");
        } catch (IOException e) {
            return ApiResponse.error(ResponseCode.INTERNAL_SERVER_ERROR,"Error deleting file chunks: " + e.getMessage());
        }
    }

    @GetMapping("/check")
    public ApiResponse  getFileChunk(FileChunkQuery query){
            List<Integer> fileChunk = fileStorageService.getFileChunk(query);
            return ApiResponse.success(fileChunk);
    }
}
